#define _CRT_SECURE_NO_WARNINGS 1

#include <vector>
#include <time.h>
using namespace std;

class Solution {
public:

    int qfind(vector<int>& nums, int begin, int end, int k)
    {
        if (begin == end) return nums[begin];
        int left = begin - 1, right = end + 1, i = begin;
        int keyi = rand() % (end - begin + 1) + begin;
        int key = nums[keyi];
        while (i < right)
        {
            if (nums[i] < key) swap(nums[++left], nums[i++]);
            else if (nums[i] == key) ++i;
            else swap(nums[--right], nums[i]);
        }
        //int a = left - begin + 1;
        int b = right - left - 1;
        int c = end - right + 1;
        if (c >= k) return qfind(nums, right, end, k);
        else if (b + c >= k) return key;
        else return qfind(nums, begin, left, k - b - c);
    }
    int findKthLargest(vector<int>& nums, int k) {
        srand(time(nullptr));
        return qfind(nums, 0, nums.size() - 1, k);
    }
};